package com.ciwong.epaper.modules.epaper.ui.newlistenspeak;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.ciwong.ciwongwrite.widget.CWToast;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.LsRedoAnswersEvent;
import com.ciwong.epaper.modules.dbbean.AnswerContent;
import com.ciwong.epaper.modules.dbbean.LswAnswer;
import com.ciwong.epaper.modules.dbbean.LswProgress;
import com.ciwong.epaper.modules.epaper.adapter.AnswerCardAdapter;
import com.ciwong.epaper.modules.epaper.bean.Attachments;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.epaper.bean.ListenspeakExam;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleSet;
import com.ciwong.epaper.modules.epaper.bean.OptionDetail;
import com.ciwong.epaper.modules.epaper.bean.OptionInfo;
import com.ciwong.epaper.modules.epaper.bean.QuestionRule;
import com.ciwong.epaper.modules.epaper.bean.QuestionScore;
import com.ciwong.epaper.modules.epaper.bean.Questions;
import com.ciwong.epaper.modules.epaper.bean.RecordSubmitPart;
import com.ciwong.epaper.modules.epaper.bean.ResourceDetail;
import com.ciwong.epaper.modules.epaper.dao.LswDao;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.me.bean.WorkContents;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.download.DownLoadDB;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.libs.audio.recorder.Mp3Recorder;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.DateFormat;
import com.ciwong.libs.utils.FileUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.CWDialog;
import com.ciwong.mobilelib.widget.ProgessBeakPoint;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import static com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil.State.READY_CHILD_QUESTION;
import static com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil.State.READY_SMALL_QUESTION;

/**
 * Created by Administrator on 2017/2/10.
 */
public abstract class NewBaseListenSpeakActivity extends BaseActivity {

    //private final String TAG = this.getClass().getSimpleName();
    private final String TAG = "retryscore";
    //文件下载项描述信息
    protected DownLoadInfo mDownLoadInfo;
    //章节详细内容
    protected Module mModule;
    protected int position;
    protected String mClassId;
    protected String checkedResource;
    protected int lsMode;
    protected int doWorkType;
    protected boolean isStopHandler = false;// handler是否停止
    protected String intentWorkId = "0";
    protected long effectivDate = 0;
    protected int mServiceId;
    protected boolean isNewVersion = false;// 是否是新版
    protected ScrollView container;
    protected ProgessBeakPoint bottomProgress;
    //    protected View make_score_view;
    protected SeekBar seek_bar_make_score;
    protected TextView bottomNo;
    protected TextView tx_record_continue_tips;
    protected static final int REQUEST_CODE_FOR_LONG_OR_SHORT = 10001;
    //做题记录
    protected String uuid = UUID.randomUUID().toString();
    //    protected int checkedIndex = -1;
    protected boolean isShowTime = true; //间隔时间内不需要显示倒计时
    protected int playCount;// 播放计数
    protected boolean isPlayAgain = false;// 是否是再一次播放
    protected boolean lookFlag = false;
    protected int timeCount;// 递减计时(秒)
    protected int progress;// seekbar的进度
    //听说模考试卷
    protected ListenspeakExam mExamData;
    protected Dialog answerCardDialog;//听说模考调试窗口
    protected AnswerCardAdapter cardAdapter;// 听说模考调试窗口 答题卡适配器
    protected boolean isRecordFail = false;
    //匹配是否打分
    public static ListenSpeakUtil.IRefreshDoRecord iRefreshDoRecord;
    protected WorkContents mWorkContents;
    protected long startTime;

    protected String mResourceName;
    public boolean isShowTips = false;
    /**
     * 当前状态
     * START, // 考试开始 BIG_QUESTION_STEM, // 播放大题题干音频 LOOK_SMALL_QUESTION, // 小题阅题 SMALL_QUESTION_STEM, // 播放小题音频
     * READY_SMALL_QUESTION, // 小题准备 LOOK_CHILD_QUESTION, // 子题阅题 CHILD_QUESTION_STEM, // 播放子题音频 READY_CHILD_QUESTION, // 小题准备
     * ANSWER, // 答题/录音 END_AUDIO, // 录音结束 END;// 考试结束
     */
    protected ListenSpeakUtil.State status = ListenSpeakUtil.State.START;
    protected int mQuesTotal = 0;// 题目总数
    protected int mQuesTotalIndex = 0;// 题目总下标
    protected int mBigQuesIndex = 0;// 当前大题下标
    protected int mSmallQuesIndex = 0;// 当前小题下标
    protected int mChildQuesIndex = -1;// 当前子题下标
    //大题题号
    protected int bigQuesIndex;
    protected int totalQuesIndex;
    protected String quesNo;
    //    // 答案List  答案记录根据versionID 唯一标识
    protected int mQuestionType = Questions.QuestionType.QUESTION_TYPE_CHOICE;// 当前小题或子题类型，默认选择题
    //匹配是否打分
    protected boolean isStopFlag = false;// 区分是否是手动停止语音播放

    protected Activity mActivity;

    protected long startDate = System.currentTimeMillis();// (开始做作业时间)(毫秒)

    protected int workTime;// 用时(秒)
    /**
     * 新需求全部走api 评测，所以要另外录音文件
     */
    protected Mp3Recorder mp3Recorder;
    /**
     * 题目的UI
     */
    protected QuestionLayout question_layout;

    private View lsw_root_view;

    protected boolean showSkipBtn = true;

    /**
     * 倒计时结束
     */
    protected abstract void onTimeOver(ListenSpeakUtil.State timeOverType);

    /**
     * 倒计时结束
     */
    protected abstract void onPlayBigStem();

    /**
     * 底部UI
     */
    protected LsBottomView ls_bottom_view;

    protected ArrayList<LswAnswer> mLswAnswerList = new ArrayList<LswAnswer>();

    protected ArrayList<ResourceDetail> isDoRecords = new ArrayList<>();// 是否做过的记录


    protected boolean isReadBigQuestionStem = true;

    //提前完成录音
    protected boolean mAheadRecord = false;

    protected int mReadyTime = 0;

    //阅题时间，用于第一次提示语是否展示的条件
    protected int mReadTime = 0;

    protected int mRetryIndex = 0;


    protected List<ResourceDetail> mResourceList;

    protected ArrayList<LswAnswer> ReDolswAnswerArrayList;

    //是否来自订正错题
    protected boolean isCorrect;

    //计时
    protected Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (isFinishing()) {
                return;
            }
            if (isStopHandler) {
                isStopHandler = false;
                return;
            }
            int msgType = msg.what;
            switch (msgType) {
                case ListenSpeakUtil.HandlerWhat.TOTAL_TIMER:// 总计时
                    workTime = workTime + 1;
                    question_layout.setShowTotalTime(DateFormat.showTime(workTime));
                    // CWLog.d(TAG, "总时间:" + workTime);
                    removeHandlerMsg(ListenSpeakUtil.HandlerWhat.TOTAL_TIMER, mHandler);
                    //这里逻辑有问题啊
                    if (workTime > 0) {
                        sendEmptyMessageDelayed(ListenSpeakUtil.HandlerWhat.TOTAL_TIMER, 1000);
                    }
                    break;
                case ListenSpeakUtil.HandlerWhat.UPDATE_TIME:// 倒计时更新时间 （准备时间倒计时，阅题倒计时，答题（录音）倒计时）
                    // 递减计时
                    if (timeCount > 0) {

                        timeCount--;
                        progress++;
                        removeMessages(ListenSpeakUtil.HandlerWhat.UPDATE_TIME);
                        int strResId = -1;


                        switch (status) {
                            case LOOK_SMALL_QUESTION:// 小题阅题
                            case LOOK_CHILD_QUESTION: // 子题阅题
                                strResId = R.string.look_question;
                                break;
                            case READY_SMALL_QUESTION:// 小题准备
                            case READY_CHILD_QUESTION:// 小题准备
                                strResId = R.string.ready_read;
                                break;
                            case ANSWER:
                                //选择题  填空题
                                //答题倒计时
                                strResId = mQuestionType == Questions.QuestionType.QUESTION_TYPE_CHOICE || mQuestionType == Questions.QuestionType.QUESTION_TYPE_FILL_BLANK ? R.string.answer_question : R.string.answer_audio;
                            default:
                                break;
                        }
                        if (strResId > 0) {

                            sendEmptyMessageDelayed(ListenSpeakUtil.HandlerWhat.UPDATE_TIME, 1000);

                            Spannable span = new SpannableString(getString(R.string.tip_timer2, getString(strResId), String.valueOf(timeCount)));
                            span.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_light_green)), span.toString().indexOf("余") + 1, span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                            if (strResId == R.string.answer_audio) {
                                ls_bottom_view.updateTimer(span, progress, showSkipBtn, LsBottomView.SKIP_TYPE_RECORD, status, false);
                            } else if (strResId == R.string.answer_question) {

                                boolean isLastQues = false;
                                if (lsMode == ListenSpeakUtil.LsMode.RETRY_MODE) {
                                    isLastQues = ListenSpeakUtil.isLastQuestionOnRetryMode(mResourceList, mBigQuesIndex, mSmallQuesIndex, mChildQuesIndex);
                                } else {
                                    isLastQues = ListenSpeakUtil.isLastQuestion(mResourceList, mBigQuesIndex, mSmallQuesIndex, mChildQuesIndex);
                                }

                                if (mQuestionType == Questions.QuestionType.QUESTION_TYPE_CHOICE) {
                                    ls_bottom_view.updateTimer(span, progress, showSkipBtn, LsBottomView.SKIP_TYPE_CHOICE, status, isLastQues);

                                } else if (mQuestionType == Questions.QuestionType.QUESTION_TYPE_FILL_BLANK) {
                                    ls_bottom_view.updateTimer(span, progress, showSkipBtn, LsBottomView.SKIP_TYPE_BLANK, status, isLastQues);
                                }
                            } else {
                                ls_bottom_view.updateTimer(span, progress, showSkipBtn, LsBottomView.SKIP_TYPE_COUNT_DOWN, status, false);
                            }
                        }

                    } else {// 计时结束
                        removeHandlerMsg(ListenSpeakUtil.HandlerWhat.UPDATE_TIME, mHandler);
                        mAheadRecord = false;
                        try {
                            onTimeOver(status);
                        } catch (NullPointerException e) {

                        }

                    }
                    break;

                default:
                    break;
            }
        }
    };


    @Override
    protected void preCreate() {
        super.preCreate();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        mDownLoadInfo = (DownLoadInfo) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_DOWNLOAD_INFO);
        mModule = (Module) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
        position = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_POSITION, 0);
        mClassId = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_CLASS_ID);
        checkedResource = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_CHECKED_RESOURCE);
        doWorkType = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_DO_WORK_TYPE, 0);
        lsMode = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_ACTION, 0);
        String workId = getIntent().getStringExtra(IntentFlag.INTENT_FLAG_WORK_ID);
        effectivDate = getIntent().getLongExtra(IntentFlag.INTENT_FLAG_WORK_EFFECTIV_TIME, -1);
        mWorkContents = (WorkContents) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_LSW_WORK_CONTENTS);
        isCorrect = getIntent().getBooleanExtra(IntentFlag.INTENT_FLAG_CORRECT, false);
        if (mWorkContents != null && mWorkContents.getExamMode() != 0 && doWorkType != 1) {
            showSkipBtn = false;
        } else {
            showSkipBtn = true;
        }
        ReDolswAnswerArrayList = (ArrayList<LswAnswer>) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_LISTEN_SPEAK_ANSWERS);
        if (!TextUtils.isEmpty(workId)) {
            intentWorkId = workId;
        }

        mServiceId = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_SERVICE_ID, -1);
        isNewVersion = !EConstants.JSON_VERSION.equalsIgnoreCase(getIntent().getStringExtra(IntentFlag.INTENT_FLAG_STR));

        mRetryIndex = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_REDO_QUES_INDEX, 0);


        if (mDownLoadInfo != null && mDownLoadInfo.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_NEW) {
            mResourceName = mDownLoadInfo.getResourceName();
        } else {
            deleteResourceIfNull(mModule, mDownLoadInfo);
            mResourceName = mModule.getResourceList().get(position).getResourceName();
        }
        //获取本地保存的开始时间
        startTime = CWSys.getSharedLong(ListenSpeakUtil.getAnswerStartTimeKey(mDownLoadInfo, mModule, position, intentWorkId), 0);
        //本地没有则使用传过来的开始时间 并保存本地
        if (startTime == 0) {
            if (null != mDownLoadInfo) {
                startTime = mDownLoadInfo.getStartTime();
                CWSys.setSharedLong(ListenSpeakUtil.getAnswerStartTimeKey(mDownLoadInfo, mModule, position, intentWorkId), startTime);
            }
        }
    }


    @Override
    protected int setView() {
        return R.layout.new_listen_speak_work;
    }


    @Override
    protected void findViews() {
        container = findViewById(R.id.ls_container);
        question_layout = findViewById(R.id.question_layout);
        if (isNewVersion) {
            question_layout.setTitleVisibility(View.GONE);
        }
        ls_bottom_view = findViewById(R.id.ls_bottom_view);
        bottomProgress = findViewById(R.id.bottom_progress);
        bottomNo = findViewById(R.id.bottom_no);
//        make_score_view = findViewById(R.id.make_score_view);
        seek_bar_make_score = findViewById(R.id.seek_bar_make_score);
        tx_record_continue_tips = findViewById(R.id.tx_record_continue_tips);

        lsw_root_view = findViewById(R.id.lsw_root_view);

        if (mWorkContents != null && mWorkContents.getExamMode() != 0 && doWorkType != 1) {
            ls_bottom_view.setShowNextTips(false);
        } else {
            ls_bottom_view.setShowNextTips(true);
        }
    }

    @Override
    protected void initEvent() {

        setGoBackListener(new GoBackListener() {
            @Override
            public void goBack() {
                dealBack();
            }
        });
        ls_bottom_view.setOnSkipListener(mSkipListener);
        ls_bottom_view.setOnBlankSkipListener(mSkipListener);

    }

    View.OnClickListener mSkipListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            next();//下一步操作
        }
    };

    protected void next() {
        // 计时结束
        switch (status) {
            case BIG_QUESTION_STEM:
                AudioPlayer.getInstance().stop();
                break;
            case SMALL_QUESTION_STEM:
            case CHILD_QUESTION_STEM:
                AudioPlayer.getInstance().stop();
                //removeHandlerMsg(ListenSpeakUtil.HandlerWhat.PLAY_SOUND, mRecorderHandler);
                break;
            default:
                removeHandlerMsg(ListenSpeakUtil.HandlerWhat.UPDATE_TIME, mHandler);
                timeCount = 0;
                mAheadRecord = true;
                onTimeOver(status);
                break;
        }

    }


    @Override
    protected void init() {
        mActivity = this;
        registListenerHome();
//        createPhoneListener();
//        controlKeyboardLayout(lsw_root_view,question_layout);
    }

    @Override
    protected void loadData() {
    }

    @Override
    public void onBackPressed() {
        dealBack();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }


    /**
     * 返回
     */
    private void dealBack() {
        if (null != mWorkContents && mWorkContents.getExamMode() == 2) {
            ToastUtil.INSTANCE.toastCenter(mActivity, R.string.work_go_back_tips);
        } else if (lsMode == ListenSpeakUtil.LsMode.RETRY_MODE) {
            finish();
        } else {
            try {
                showConfirmEndDialog();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }


    /**
     * 播放完附件音频后
     * 开始进入子题或开始阅题
     */
    protected void startChidQuesOrLook(List<ResourceDetail> mResourceList) {
        if (status == ListenSpeakUtil.State.SMALL_QUESTION_STEM) {// 小题播放完毕后如果还有子题就直接进入子题

            if (mSmallQuesIndex == 0) {
                List<Questions> smallQuesList = mResourceList.get(mBigQuesIndex)
                        .getQuestions();
                List<Questions> childQuesList = smallQuesList
                        .get(mSmallQuesIndex).getChildren();
                if (childQuesList != null && !childQuesList.isEmpty()) {
                    mChildQuesIndex = 0;
                    startLoadChildQuestion(childQuesList.get(mChildQuesIndex), false, mResourceList);
                    return;
                }
            }
        }

        if (lookFlag) {

            QuestionRule listeningAndSpeakingRule = mResourceList.get(mBigQuesIndex).getTemplateSettings().getListeningAndSpeakingRule();
            startReady(listeningAndSpeakingRule.getReadyTime(), false);
            lookFlag = false;

        } else {
            //neo-进入录音准备
            int lookTime = mResourceList.get(mBigQuesIndex).getTemplateSettings().getListeningAndSpeakingRule().getLookTime();// 取得阅题时间
            status = ListenSpeakUtil.State.LOOK_CHILD_QUESTION;
            startLookQuestion(lookTime);
        }
    }


    /**
     * 开始阅题
     */
    protected void startLookQuestion(int lookTime) {
        ls_bottom_view.microRecordingSetVisibility(View.GONE);
        playCount = 0;
//        removeHandlerMsg(ListenSpeakUtil.HandlerWhat.PLAY_SOUND, mHandler);
        // 进入阅题状态
        timeCount = lookTime;
        mReadTime = lookTime;
        printState();
        progress = 0;
//        ls_bottom_view.updateTimer(null, progress,true,LsBottomView.SKIP_TYPE_COUNT_DOWN,status);
        ls_bottom_view.seekBarSetMax(timeCount);
        removeHandlerMsg(ListenSpeakUtil.HandlerWhat.UPDATE_TIME, mHandler);
        mHandler.sendEmptyMessage(ListenSpeakUtil.HandlerWhat.UPDATE_TIME);
    }


    /**
     * 开始准备倒计时
     * 发送更新时间消息
     *
     * @param readyTime
     * @param isSmallReady
     */
    protected void startReady(int readyTime, boolean isSmallReady) {
        playCount = 0;
        status = isSmallReady ? READY_SMALL_QUESTION
                : READY_CHILD_QUESTION;
        // 进入准备状态
        printState();
        timeCount = readyTime;
        mReadyTime = readyTime;

        progress = 0;
//        ls_bottom_view.updateTimer(null, progress,true,LsBottomView.SKIP_TYPE_COUNT_DOWN,status);
        ls_bottom_view.seekBarSetMax(timeCount);
        removeHandlerMsg(ListenSpeakUtil.HandlerWhat.UPDATE_TIME, mHandler);
        mHandler.sendEmptyMessage(ListenSpeakUtil.HandlerWhat.UPDATE_TIME);
    }


    /**------------------------加载题目资源相关开始--------------------------------**/


    /**
     * 开始加载小题题干和附件
     *
     * @param question
     */
    protected void startLoadSmallQuestion(List<ResourceDetail> mResourceList, Questions question) {
        startLoadSmallQuestion(mResourceList, question, false);
    }

    /**
     * 开始加载小题题干和附件
     *
     * @param question
     * @param isFromLook
     */
    protected void startLoadSmallQuestion(List<ResourceDetail> mResourceList, Questions question, boolean isFromLook) {
        try {
            status = isFromLook ? ListenSpeakUtil.State.SMALL_QUESTION_STEM
                    : ListenSpeakUtil.State.LOOK_SMALL_QUESTION;
            OptionDetail optionsDetail = question.getTrunk();
            //增加小题序号
            String textTitle;
            String textScore = ListenSpeakUtil.getChildQuestionScore(question, mResourceList.get(mBigQuesIndex).getScores());
            if (question.getSort() != null && !"".equals(question.getSort())) {
                //textTitle = question.getSort() + "、" + textScore + optionsDetail.getBody();
                textTitle = textScore + optionsDetail.getBody();
            } else {
                textTitle = optionsDetail.getBody();
                if (!"".equals(textTitle)) {
                    if (!"".equals(textScore)) {
                        StringBuffer stringBuffer = new StringBuffer(textTitle);
                        stringBuffer.insert(2, textScore);
                        textTitle = stringBuffer.toString();
                    }
                } else {
                    textTitle = textScore;
                }
            }

            question_layout.setSmallQuestionStem(textTitle);
            //选项

            Log.d(TAG, "######  startLoadSmallQuestion loadOptionLayout ######" + status);
//            mQuestionType = question.getType();//lzh
//            question_layout.loadOptionLayout(question.getOptions(), mQuestionType);

            // (当类型为5的时候，root开头的那3个字段才有用)
            QuestionRule listeningAndSpeakingRule = mResourceList.get(mBigQuesIndex)
                    .getTemplateSettings().getListeningAndSpeakingRule();
            //是否是阅读理解题
            boolean isReadQues = question
                    .getType() == Questions.QuestionType.QUESTION_TYPE_READ;// 是否是阅读理解题
            int rootLookTime = isReadQues
                    ? listeningAndSpeakingRule.getRootLookTime()
                    : listeningAndSpeakingRule.getLookTime();// 取得阅题时间

            if (isFromLook) {
                int rootAudioViews = isReadQues
                        ? listeningAndSpeakingRule.getRootAudioViews()
                        : listeningAndSpeakingRule.getAudioViews();// 音频播放次数
                int rootReadyTime = isReadQues
                        ? listeningAndSpeakingRule.getRootReadyTime()
                        : listeningAndSpeakingRule.getReadyTime();
                startLoadAttachments(optionsDetail, rootAudioViews, rootLookTime,
                        rootReadyTime, isFromLook, true);

                question_layout.startLoadImg(optionsDetail, ls_bottom_view.getSeekBarView());

            } else {
                question_layout.startLoadImg(optionsDetail, ls_bottom_view.getSeekBarView());
                startLookQuestion(rootLookTime);
            }
        } catch (Exception e) {
            ToastUtil.INSTANCE.toastCenterError("加载题目失败,异常...");
            e.getStackTrace();
            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, "加载题目失败,异常..." + e.getMessage(), "加载题目startLoadSmallQuestion失败Exception");
        }

    }


    /**
     * 开始加载子题题干和附件
     *
     * @param childQuestion
     */
    protected void startLoadChildQuestion(Questions childQuestion,
                                          boolean isFromLook, List<ResourceDetail> mResourceList) {
        status = isFromLook ? ListenSpeakUtil.State.CHILD_QUESTION_STEM
                : ListenSpeakUtil.State.LOOK_CHILD_QUESTION;

        printState();
        ResourceDetail mResourceDetail = mResourceList.get(mBigQuesIndex);
        OptionDetail optionsDetail = childQuestion.getTrunk();
        //当TYPE==5的时候  不是填空题时候  题目序号取子题sort
        //题号加在提干前面 用空格分开  只针对于新资源  老资源不管
        String textTitle;
        String textScore = ListenSpeakUtil.getChildQuestionScore(childQuestion, mResourceDetail.getScores());
        if (childQuestion.getSort() != null && !"".equals(childQuestion.getSort())) {
            //textTitle = childQuestion.getSort() + "、" + textScore + optionsDetail.getBody();
            //去除小题题号
            textTitle = textScore + optionsDetail.getBody();
        } else {
            textTitle = optionsDetail.getBody();
            if (!"".equals(textTitle)) {
                if (!"".equals(textScore)) {
                    StringBuffer stringBuffer = new StringBuffer(textTitle);
                    stringBuffer.insert(2, textScore);
                    textTitle = stringBuffer.toString();
                }
            } else {
                textTitle = textScore;
            }
        }
        Log.d(TAG, "######  textTitle ######" + textTitle);
        question_layout.setChildQuestionStem(textTitle, isNewVersion);

        mQuestionType = childQuestion.getType();
        Log.d(TAG, "######  startLoadChildQuestion loadOptionLayout ######" + status);
        if (!isFromLook) {
            question_layout.loadOptionLayout(childQuestion.getOptions(), mQuestionType);// 加载子题选项
        }
        QuestionRule listeningAndSpeakingRule = mResourceDetail.getTemplateSettings().getListeningAndSpeakingRule();
        int lookTime = listeningAndSpeakingRule.getLookTime();// 取得阅题时间


        if (isFromLook) {
            int audioViews = listeningAndSpeakingRule.getAudioViews();// 音频播放次数
            int readyTime = listeningAndSpeakingRule.getReadyTime();
            startLoadAttachments(optionsDetail, audioViews, lookTime, readyTime,
                    isFromLook, false);
        } else {
            //重新加载下图片控件,避免控件刷新不协调
            question_layout.startLoadAttachmentsOnlyImg(optionsDetail, ls_bottom_view.getSeekBarView());
            startLookQuestion(lookTime);
        }
    }

    /**
     * 开始加载附件
     *
     * @param optionsDetail
     * @param audioViews    音频播放次数
     * @param lookTime      看题时间
     * @param readyTime     准本时间
     * @param isFromLook    是否来自
     * @param isSmallReady  是否来自
     */
    protected void startLoadAttachments(OptionDetail optionsDetail,
                                        int audioViews, int lookTime, int readyTime, boolean isFromLook,
                                        boolean isSmallReady) {
        // 取附件集合
        final List<Attachments> attachmentsList = optionsDetail.getAttachments();
        List<String> audioUrlList = new ArrayList<String>();
        if (attachmentsList != null && !attachmentsList.isEmpty()) {
            // 取出所有的图片或语音地址
            List<String> imgUrlList = new ArrayList<String>();
            for (int i = 0; i < attachmentsList.size(); i++) {
                Attachments attachments = attachmentsList.get(i);
                if (attachments != null) {
                    String url = attachments.getUrl();
                    if (!TextUtils.isEmpty(url)) {
                        switch (attachments.getFileType()) {
                            case Attachments.AttachmentFileType.ATTACHMENT_FILE_TYPE_IMG:// 图片
                                imgUrlList.add(ESystem.formatPath(url));
                                break;
                            case Attachments.AttachmentFileType.ATTACHMENT_FILE_TYPE_AUDIO:// 语音
                                audioUrlList.add(ESystem.formatPath(url));
                                break;
                        }
                    }
                }
            }

            if (!imgUrlList.isEmpty()) {
                question_layout.imgContainerRemoveAllViews();
                for (int i = 0; i < imgUrlList.size(); i++) {
                    if (i == 0) {

                        ls_bottom_view.seekBarSetVisibility(View.GONE);

                        question_layout.imgContainerSetVisibility(View.VISIBLE);
                    }

                    question_layout.showImg(imgUrlList.get(i), i, imgUrlList);
                }
            }

            if (!audioUrlList.isEmpty()) {
                //播放附件里的语音
                loadAttachmentsAudio(audioViews, audioUrlList);
            } else {
                CWLog.d("听说模考：", "audioUrlList为空");
                lookFlag = isFromLook;
                attachmentExceptionOrStoped();
            }

        } else {// 没有附件的简答题
            //lzh 没有附件的其他题型（异常情况）
            CWLog.d("听说模考：", "没有附件的简答题 isFromLook：" + isFromLook);
            attachmentNull(isFromLook, lookTime, readyTime, isSmallReady);
        }

    }

    /**
     * 当附件音频为空或者资源音频播放结束
     */

    protected void attachmentExceptionOrStoped() {

        boolean isInfoRetail;
        int infoRetail = -1;

        if (mBigQuesIndex < mResourceList.size()) {
            infoRetail = mResourceList.get(mBigQuesIndex).getTemplateSettings().getInfoRetail();
        }
        if (mBigQuesIndex < mResourceList.size()) {
            isInfoRetail = mResourceList.get(mBigQuesIndex).getTemplateSettings().getListeningAndSpeakingRule().getInfoRetail() != 0;
        } else {
            isInfoRetail = false;
        }


        // 播放小题音频
        if (status == ListenSpeakUtil.State.SMALL_QUESTION_STEM) {
            if (mBigQuesIndex < mResourceList.size()) {
                QuestionRule listeningAndSpeakingRule = mResourceList.get(mBigQuesIndex).getTemplateSettings().getListeningAndSpeakingRule();
                //题目类型:阅读理解题
                startReady(mQuestionType == Questions.QuestionType.QUESTION_TYPE_READ ? listeningAndSpeakingRule.getRootReadyTime() : listeningAndSpeakingRule.getReadyTime(), true);
            }
        } else if (isInfoRetail) {
            if (mBigQuesIndex < mResourceList.size()) {
                List<Questions> smallQuesList = mResourceList.get(mBigQuesIndex).getQuestions();
                List<Questions> childQuesList = smallQuesList.get(mSmallQuesIndex).getChildren();
                //切换子题
                switchChildQuestion(childQuesList.get(mChildQuesIndex), mResourceList);
            }
            //自主提问播放子题音频资源切换到下一题
        } else if (infoRetail == 2) {
            autoSwitchNextQuestion(mResourceList);
        } else {
            //开始进入子题或开始阅题
            startChidQuesOrLook(mResourceList);

        }
    }

    /**
     * 当没有附件或者附件音频为空或者资源音频播放结束
     */

    protected void attachmentNull(boolean isFromLook, int lookTime, int readyTime, boolean isSmallReady) {

        boolean isInfoRetail = false;
        int infoRetail = -1;
        if (mBigQuesIndex < mResourceList.size()) {
            infoRetail = mResourceList.get(mBigQuesIndex).getTemplateSettings().getInfoRetail();
        }
        if (mBigQuesIndex < mResourceList.size()) {
            isInfoRetail = mResourceList.get(mBigQuesIndex).getTemplateSettings().getListeningAndSpeakingRule().getInfoRetail() != 0;
        } else {
            isInfoRetail = false;
        }
        if (status == ListenSpeakUtil.State.SMALL_QUESTION_STEM) {
            if (mBigQuesIndex < mResourceList.size()) {
                QuestionRule listeningAndSpeakingRule = mResourceList.get(mBigQuesIndex).getTemplateSettings().getListeningAndSpeakingRule();
                //题目类型:阅读理解题
                startReady(mQuestionType == Questions.QuestionType.QUESTION_TYPE_READ ? listeningAndSpeakingRule.getRootReadyTime() : listeningAndSpeakingRule.getReadyTime(), true);
            }
        } else {
            if (isInfoRetail) {
                List<Questions> smallQuesList = mResourceList.get(mBigQuesIndex).getQuestions();
                List<Questions> childQuesList = smallQuesList.get(mSmallQuesIndex).getChildren();
                //切换子题
                switchChildQuestion(childQuesList.get(mChildQuesIndex), mResourceList);
                //自主提问播放子题音频资源切换到下一题
            } else if (infoRetail == 2) {
                autoSwitchNextQuestion(mResourceList);
            } else {// 没有附件的简答题
                //开始进入子题或开始阅题
                startNext(mResourceList, isFromLook, lookTime, readyTime, isSmallReady);
            }
        }
    }

    /**
     * lzh
     * 播放完附件音频后
     * 开始进入子题或开始阅题
     */
    protected void startNext(List<ResourceDetail> mResourceList, boolean isFromLook, int lookTime, int readyTime, boolean isSmallReady) {
        if (status == ListenSpeakUtil.State.SMALL_QUESTION_STEM) {// 小题播放完毕后如果还有子题就直接进入子题
            QuestionRule listeningAndSpeakingRule = mResourceList.get(mBigQuesIndex).getTemplateSettings().getListeningAndSpeakingRule();
            if (isFromLook && readyTime > 0) {//当是题干时，阅完题进入准备时间
                startReady(readyTime, isSmallReady);
                return;
            }
            if (mSmallQuesIndex == 0) {
                List<Questions> smallQuesList = mResourceList.get(mBigQuesIndex)
                        .getQuestions();
                List<Questions> childQuesList = smallQuesList
                        .get(mSmallQuesIndex).getChildren();
                if (childQuesList != null && !childQuesList.isEmpty()) {
                    mChildQuesIndex = 0;
                    startLoadChildQuestion(childQuesList.get(mChildQuesIndex), false, mResourceList);
                    return;
                }
            }
        }

        if (isFromLook) {
            startReady(readyTime, isSmallReady);
        } else {
            startLookQuestion(lookTime);
        }
    }


    /**
     * 播放附件里的语音
     * 播放第一个附件音频
     */
    protected void loadAttachmentsAudio(int audioViews, List<String> audioUrlList) {
        playCount = audioViews;
        lookFlag = true;
        ls_bottom_view.showPlayButton(mQuestionType);
        isPlayAgain = false;
        try {
            AudioPlayer.getInstance().play(audioUrlList.get(0));// 播放第一个附件音频
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M && EApplication.getInstance().mPlayerspeed != 1.0f) {
                MediaPlayer mMediaPlayer = AudioPlayer.getInstance().getMediaPlayer();
                if (mMediaPlayer != null) {
                    try {
                        PlaybackParams params = mMediaPlayer.getPlaybackParams().setSpeed(EApplication.getInstance().mPlayerspeed);
                        if (params != null) {
                            mMediaPlayer.setPlaybackParams(params);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**------------------------加载题目资源相关结束--------------------------------**/


    /**------------------------切换题目相关开始--------------------------------**/


    /**
     * 自动切换到下一题
     *
     * @param
     */
    protected void autoSwitchNextQuestion(List<ResourceDetail> mResourceList) {

        ls_bottom_view.microRecordingSetVisibility(View.GONE);

        if (mp3Recorder != null && mp3Recorder.isRecording()) {
            isStopFlag = true;
            mp3Recorder.stop();
        }
        startSwitchNextQuestion(mResourceList);
    }


    /**
     * 开始切换到下一题
     */
    protected void startSwitchNextQuestion(List<ResourceDetail> mResourceList) {
        Log.d(TAG, "#########切题 关闭选择题可答题#########");
        question_layout.allowAnswer(true);
        //当前层级是否有子题，子题遍历，是否有小题，小题是否遍历完，大题遍历
        if (isFinishing()) {
            return;
        }
        List<Questions> smallQuesList = mResourceList.get(mBigQuesIndex).getQuestions();
        List<Questions> childQuesList = null;

        // 有小题
        if (smallQuesList != null && !smallQuesList.isEmpty() && mSmallQuesIndex < smallQuesList.size()) {
            childQuesList = smallQuesList.get(mSmallQuesIndex).getChildren();
        }

        if (childQuesList != null && !childQuesList.isEmpty()
                && mChildQuesIndex < childQuesList.size()) // 且有子题
        {
            //为选择填空题判断的有子题
            if (mChildQuesIndex != -1) {
                // 当前子题
                Questions childQuestion = childQuesList.get(mChildQuesIndex);
                //开始请求接口 提交选择填空题答案，不是录音文件
                if (childQuestion.getType() == Questions.QuestionType.QUESTION_TYPE_CHOICE || childQuestion.getType() == Questions.QuestionType.QUESTION_TYPE_FILL_BLANK) {
                    LswAnswer lswAnswer = getChildOrFillBlankOrChoice(mResourceList, childQuestion);
                    if (null != lswAnswer) {
                        //缓存答案 添加用户答案
                        startMakeScoreRequestAndSaveAnswer(lswAnswer);
                    }
                }
            }
        }

        if (childQuesList != null && !childQuesList.isEmpty() && mChildQuesIndex < childQuesList.size() - 1) // 且有子题
        {
            loadSwitchAnim();
            // 切换到 下一子题
            mChildQuesIndex++;
            mQuesTotalIndex++;
            updateAnswerCardSelect();
            Questions childQues = childQuesList.get(mChildQuesIndex);

            if (!ListenSpeakUtil.questionTypeIsExist(childQues.getType())) {
                showToastError(R.string.question_type_not_exist);
                startSwitchNextQuestion(mResourceList);
                return;
            }
            switchChildQuestion(childQues, mResourceList);
        } else {
            //没有子题,或者子题遍历完
            boolean isSaveBigQuesIndex = true;

            mChildQuesIndex = -1;

            if (smallQuesList != null && !smallQuesList.isEmpty()) {
                // 当前小题
                Questions smallQuestion = smallQuesList.get(mSmallQuesIndex);
                if (smallQuestion.getType() == Questions.QuestionType.QUESTION_TYPE_CHOICE || smallQuestion.getType() == Questions.QuestionType.QUESTION_TYPE_FILL_BLANK) {
                    LswAnswer lswAnswer = getChildOrFillBlankOrChoice(mResourceList, smallQuestion);
                    if (null != lswAnswer) {
                        //缓存答案 添加用户答案
                        startMakeScoreRequestAndSaveAnswer(lswAnswer);
                    }
                }
            }

            if (smallQuesList != null && mSmallQuesIndex < smallQuesList.size() - 1) {// 下一小题
                loadSwitchAnim();
                mSmallQuesIndex++;
                mQuesTotalIndex++;
                updateAnswerCardSelect();

                Questions smallQues = smallQuesList.get(mSmallQuesIndex);
                if (!ListenSpeakUtil.questionTypeIsExist(smallQues.getType())) {
                    showToastError(R.string.question_type_not_exist);
                    startSwitchNextQuestion(mResourceList);
                    return;
                }

                question_layout.changeQuestionTitle(mBigQuesIndex, mSmallQuesIndex);
                //选择题取当前的小题序号  拼接 显示   老的资源不支持
                String textTitle;
                String textScore = ListenSpeakUtil.getChildQuestionScore(smallQues, mResourceList.get(mBigQuesIndex).getScores());
                if (smallQues.getSort() != null && !"".equals(smallQues.getSort())) {
                    //textTitle = smallQues.getSort() + "、" + textScore + smallQues.getTrunk().getBody();
                    textTitle = textScore + smallQues.getTrunk().getBody();
                } else {
                    textTitle = smallQues.getTrunk().getBody();
                    if (!"".equals(textTitle)) {
                        if (!"".equals(textScore)) {
                            StringBuffer stringBuffer = new StringBuffer(textTitle);
                            stringBuffer.insert(2, textScore);
                            textTitle = stringBuffer.toString();
                        }
                    } else {
                        textTitle = textScore;
                    }
                }

                question_layout.setSmallQuestionStem(textTitle);

                // 选择题  填空题 加载小题选项

                Log.d(TAG, "######  startSwitchNextQuestion loadOptionLayout ######" + status);
                question_layout.loadOptionLayout(smallQues.getOptions(), mQuestionType);

                int rootLookTime = ListenSpeakUtil.getLookTime(mResourceList, smallQues, mBigQuesIndex);// 取得阅题时间

                status = ListenSpeakUtil.State.LOOK_SMALL_QUESTION;

                startLookQuestion(rootLookTime);

                //neo-解决图片展示延时问题,之前是阅完题才替换之前图片，现在阅题前后加载一次图片

                if (smallQuesList != null && !smallQuesList.isEmpty()) {
                    Questions smallQuestion = smallQuesList.get(mSmallQuesIndex);
                    question_layout.startLoadImg(smallQuestion.getTrunk(), ls_bottom_view.getSeekBarView());
                }


            } else {

                if (lsMode == ListenSpeakUtil.LsMode.RETRY_MODE) {


//                    Intent intent = new Intent();
//                    intent.putExtra(IntentFlag.INTENT_FLAG_WORK_TIME, workTime);
//                    intent.putExtra(IntentFlag.INTENT_FLAG_OBJ_LIST, mLswAnswerList);
//                    intent.putExtra(IntentFlag.INTENT_FLAG_LSW_IS_DO_REDORD, isDoRecords);
//                    setResult(RESULT_OK, intent);
//                    finish();

                    LsRedoAnswersEvent lsRedoAnswersEvent = new LsRedoAnswersEvent();
                    lsRedoAnswersEvent.setIsDoRecords(isDoRecords);
                    lsRedoAnswersEvent.setLswAnswers(mLswAnswerList);
                    lsRedoAnswersEvent.setWorkTime(workTime);
                    EventBus.getDefault().post(lsRedoAnswersEvent);
                    finish();


                    return;
                } else if (mBigQuesIndex < mResourceList.size() - 1) {// 下一大题

                    loadSwitchAnim();
                    question_layout.imgContainerSetVisibility(View.GONE);

                    int currPoint = bottomProgress.getCurrentPoint() + 1;
                    bottomProgress.reDraw(currPoint);
                    bottomNo.setText(getString(R.string.show_bottom_no,
                            currPoint + 1, bottomProgress.getPoint()));

                    //自主学习
                    if (isDoRecords == null || mBigQuesIndex < 0
                            || mBigQuesIndex >= isDoRecords.size()) {
                        mSmallQuesIndex = 0;
                        mQuesTotalIndex++;
                        mBigQuesIndex++;
                        serializeBigQuesIndex(isSaveBigQuesIndex, mBigQuesIndex);
                        toNextBigQuestion(mResourceList);
                        return;
                    }

                    if (mBigQuesIndex < isDoRecords.size()) {
                        //自主学习
                        // 当前大题已做完，准备切换到下一大题
                        ResourceDetail demoo = new ResourceDetail();
                        demoo.setIndex(mBigQuesIndex);
                        isDoRecords.get(isDoRecords.indexOf(demoo)).setDo(true);
                    }

                    if (iRefreshDoRecord != null) {// 刷新选题界面
                        iRefreshDoRecord.refreshDoRecord(isDoRecords);
                    }

                    SerializableManager.getInstance().serialize(ListenSpeakUtil.getSaveIsDoRecordKey(mDownLoadInfo, mModule, position, uuid), isDoRecords);// 保存是否做的记录

                    if (mBigQuesIndex < 0) {
                        mBigQuesIndex = 0;
                    }

                    mSmallQuesIndex = 0;
                    mQuesTotalIndex++;
                    mBigQuesIndex++;
                    //serializeBigQuesIndex(isSaveBigQuesIndex, mBigQuesIndex);
                    for (; mBigQuesIndex < isDoRecords.size(); mBigQuesIndex++) {
                        boolean isDo = isDoRecords.get(mBigQuesIndex).isDo();
                        if (!isDo) {// 还没做
                            toNextBigQuestion(mResourceList);
                            break;
                        } else {// 已经做过了
                            mQuesTotalIndex++;
                        }
                    }

                    //toNextBigQuestion(mResourceList);

                } else {// 结束考试

                    if (isFinishing()) {
                        return;
                    }

                    if (isDoRecords != null && mBigQuesIndex >= 0 && mBigQuesIndex < isDoRecords.size()) {
                        // 当前大题已做完
                        ResourceDetail demoo = new ResourceDetail();
                        demoo.setIndex(mBigQuesIndex);
                        int index = isDoRecords.indexOf(demoo);
                        if (isDoRecords.size() > index && index >= 0) {
                            isDoRecords.get(index).setDo(true);
                        } else {
                            isDoRecords.get(mBigQuesIndex).setDo(true);
                        }
                        if (iRefreshDoRecord != null) {// 刷新选题界面
                            iRefreshDoRecord.refreshDoRecord(isDoRecords);
                        }

                        SerializableManager.getInstance().serialize(ListenSpeakUtil.getSaveIsDoRecordKey(mDownLoadInfo, mModule, position, uuid), isDoRecords);// 保存是否做的记录
                    }
                    ls_bottom_view.hideTimerAnimation();
                    mHandler.removeMessages(ListenSpeakUtil.HandlerWhat.TOTAL_TIMER);
                    status = ListenSpeakUtil.State.END;

                    //禁止填空题作答

                    question_layout.enableBlankInput();
                    AudioPlayer.getInstance().play(ListenSpeakUtil.SoundUrl.SOUND_END_EXAM, this, null);
                }
                serializeBigQuesIndex(isSaveBigQuesIndex, mBigQuesIndex);
            }
        }
    }


    /**
     * 去往下一大题
     */

    protected void toNextBigQuestion(List<ResourceDetail> mResourceList) {
        question_layout.setSmallQuestionStem(null);
        question_layout.setChildQuestionStem(null, isNewVersion);

        //切换大题
        switchBigQuestion(mResourceList);
        startLoadBigQuestion(mResourceList);
        updateAnswerCardSelect();
    }


    /**
     * 开始播放大题音频
     * // 进入播放大题题干状态
     */
    protected void startLoadBigQuestion(List<ResourceDetail> mResourceList) {
        try {
            // 进入播放大题题干状态
            status = ListenSpeakUtil.State.BIG_QUESTION_STEM;
            printState();
            if (mResourceList != null) {
                ResourceDetail resourceDetail = mResourceList.get(mBigQuesIndex);
                if (resourceDetail != null) {
                    ModuleSet moduleSet = resourceDetail.getTemplateSettings();

                    //用户可选择设置可以选择不播放大题题干
                    if (isReadBigQuestionStem) {
                        try {
                            AudioPlayer.getInstance().play(ESystem.formatPath(moduleSet.getAudioUrl()));// 大题题干音频
                            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M && EApplication.getInstance().mPlayerspeed != 1.0f) {
                                MediaPlayer mMediaPlayer = AudioPlayer.getInstance().getMediaPlayer();
                                if (mMediaPlayer != null) {
                                    try {
                                        PlaybackParams params = mMediaPlayer.getPlaybackParams().setSpeed(EApplication.getInstance().mPlayerspeed);
                                        if (params != null) {
                                            mMediaPlayer.setPlaybackParams(params);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        ls_bottom_view.showPlayButton(mQuestionType);

                        //大题题干高亮
                        question_layout.setBigStemHighLight(true);
                        Log.e(TAG, "startLoadBigQuestion: ");

                    } else {

                        onPlayBigStem();
                    }

                }
            }
        } catch (Exception e) {
            CWToast.error(NewBaseListenSpeakActivity.this, "播放音频失败").show();
            e.getStackTrace();
        }

    }

    /**
     * 切换大题
     * 小题题标归0
     * 状态改为开始  考试开始
     */
    protected void switchBigQuestion(List<ResourceDetail> mResourceList) {
        try {
            mSmallQuesIndex = 0;
            question_layout.changeQuestionTitle(mBigQuesIndex, mSmallQuesIndex);
            status = ListenSpeakUtil.State.START;
            final ModuleSet moduleSet = mResourceList.get(mBigQuesIndex).getTemplateSettings();// 大题模块设置

            if (moduleSet != null) {

                //young  new question of long  or short
                if (moduleSet.getIsPartView() == 1) {//short
                    EpaperJumpManager.jumpToListenSpeakWorkLongOrShortConAct(1, R.string.go_back, NewBaseListenSpeakActivity.this,
                            isDoRecords, lsMode, mBigQuesIndex, mResourceList, isShowTips, mResourceName, uuid, false, null, REQUEST_CODE_FOR_LONG_OR_SHORT, doWorkType, mQuesTotalIndex);

                    return;
                } else if (moduleSet.getInfoRetail() == 11) {
                    //long
                    EpaperJumpManager.jumpToListenSpeakWorkLongOrShortConAct(11, R.string.go_back, NewBaseListenSpeakActivity.this,
                            isDoRecords, lsMode, mBigQuesIndex, mResourceList, isShowTips, mResourceName, uuid, false, null, REQUEST_CODE_FOR_LONG_OR_SHORT, doWorkType, mQuesTotalIndex);
                    return;
                } else {
                    int questionType = question_layout.initBigQuestionAndOptions(mResourceList, mBigQuesIndex, mSmallQuesIndex, ls_bottom_view.getSeekBarView());
                    if (questionType > 0) {
                        mQuestionType = questionType;
                    }

                }


            }
        } catch (Exception e) {
            e.getStackTrace();
        }


    }


    /**
     * 切换小题
     */
    protected void switchSmallQuestion(List<ResourceDetail> mResourceList, Questions smallQuestion) {
        mQuestionType = smallQuestion.getType();
        // setOptionsEnable(false);
        question_layout.changeQuestionTitle(mBigQuesIndex, mSmallQuesIndex);
        // 加载小题
        startLoadSmallQuestion(mResourceList, smallQuestion);
        OptionDetail optionsDetail = smallQuestion.getTrunk();
        //小题序号
        //增加小题序号
        String texttitle;
        if (smallQuestion.getSort() != null && !"".equals(smallQuestion.getSort())) {
            //texttitle = smallQuestion.getSort() + "、" + optionsDetail.getBody();
            texttitle = optionsDetail.getBody();
        } else {
            texttitle = optionsDetail.getBody();
        }

        question_layout.setSmallQuestionStem(texttitle);
        question_layout.startLoadImg(optionsDetail, ls_bottom_view.getSeekBarView());
        // 加载小题选项

        Log.d(TAG, "######  switchSmallQuestion loadOptionLayout ######" + status);
        question_layout.loadOptionLayout(smallQuestion.getOptions(), mQuestionType);
    }


    /**
     * 切换子题
     *
     * @param childQuestion
     */
    protected void switchChildQuestion(Questions childQuestion, List<ResourceDetail> mResourceList) {
        mQuestionType = childQuestion.getType();
        // 加载子题
        startLoadChildQuestion(childQuestion, false, mResourceList);
    }


    /**
     * 加载切换动画
     */
    protected void loadSwitchAnim() {
        question_layout.optionsLayoutRemoveAllViews();
        container.startAnimation(AnimationUtils.loadAnimation(NewBaseListenSpeakActivity.this, R.anim.right_enter));
        question_layout.reSetCheckedIndex(-1);
//        checkedIndex = -1;
    }

    /**------------------------切换题目相关结束--------------------------------**/


    /**
     * 清除记录
     */
    protected void clearRecord() {
        // 答案记录 KEY
//        String key = ESystem.getSaveRecordKey(mDownLoadInfo, mModule, position,
//                intentWorkId, uuid,
//                SerializableManager.SerializeKey.SHARE_KEY_ANSWER_RECORD);
//        // 清除答案记录
//        SerializableManager.getInstance().serialize(key, null);

        //清除 做作业UUID
//        CWSys.setSharedString(ListenSpeakUtil.getUuidSaveKey(mDownLoadInfo, mModule, position, intentWorkId), null);
//
//        //清除保存的大题题号
//        CWSys.setSharedInt(ListenSpeakUtil.getSaveQuesNoKey(mDownLoadInfo, mModule, position, intentWorkId, uuid), 0);
//        //清除 做作业用时 时间
//        CWSys.setSharedInt(ListenSpeakUtil.getSaveTime(mDownLoadInfo, mModule, position, intentWorkId, uuid), 0);
//        //保存是否清除记录标志
//        SerializableManager.getInstance().serialize(ListenSpeakUtil.getSaveIsRestartKey(mDownLoadInfo, mModule, position, intentWorkId, uuid), false);

    }


    /**
     * 退出提示框
     */
    private void showConfirmEndDialog() {
        if (isDestroy) {
            return;
        }
        CWDialog dialog = new CWDialog(this);
        dialog.setMessage(R.string.confirm_back_work);
        dialog.setPositiveButton(android.R.string.cancel, null)
                .setNegativeButton(R.string.ok,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                                // 区分是否是手动停止语音播放
                                isStopFlag = true;
                                AudioPlayer.getInstance().stop();
                                if (mp3Recorder != null && mp3Recorder.isRecording()) {
                                    isStopFlag = true;
                                    mp3Recorder.stop();
                                }
                                finish();
                            }
                        })
                .show();
    }

    /**
     * 监听电话
     */
    private void createPhoneListener() {
        try {
            TelephonyManager telephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            telephony.listen(new OnPhoneStateListener(), PhoneStateListener.LISTEN_CALL_STATE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class OnPhoneStateListener extends PhoneStateListener {

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {

            switch (state) {
                case TelephonyManager.CALL_STATE_IDLE:
                    break;
                case TelephonyManager.CALL_STATE_RINGING:

//为了验证中途退出问题，暂时去掉监听
//                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, "finish 2，来电退出", "听说模考追踪中途finish", true);
                    if (mp3Recorder != null && mp3Recorder.isRecording()) {
                        isStopFlag = true;
                        mp3Recorder.stop();
                    }
                    NewBaseListenSpeakActivity.this.finish();

                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    break;
            }
            super.onCallStateChanged(state, incomingNumber);
        }
    }

    /**
     * 是否返回拦截
     *
     * @return
     */
    protected boolean isBack() {
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && isBack()) {
            //返回键监听
            if (null != mWorkContents && mWorkContents.getExamMode() == 2) {
                ToastUtil.INSTANCE.toastCenter(mActivity, R.string.work_go_back_tips);
            } else if (lsMode == ListenSpeakUtil.LsMode.RETRY_MODE) {
                finish();
            } else {
                try {
                    // 区分是否是手动停止语音播放
                    isStopFlag = true;
                    AudioPlayer.getInstance().stop();
                    if (mp3Recorder != null && mp3Recorder.isRecording()) {
                        isStopFlag = true;
                        mp3Recorder.stop();
                    }
                    finish();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return true;
        }
        Log.d(TAG, "###############onKeyDown##################" + keyCode);
        return super.onKeyDown(keyCode, event);


    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "###############onPause()##################");
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (!isAppOnForeground()) {
            //app 进入后台
            //全局变量isActive = false 记录当前已经进入后台
            if (lsMode == ListenSpeakUtil.LsMode.RETRY_MODE) {
                finish();
            } else {
                try {
                    // 区分是否是手动停止语音播放
                    isStopFlag = true;
                    AudioPlayer.getInstance().stop();
                    if (mp3Recorder != null && mp3Recorder.isRecording()) {
                        isStopFlag = true;
                        mp3Recorder.stop();
                    }
                    finish();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        Log.d(TAG, "###############onStop##################");
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.d(TAG, "###############onTouchEvent##################" + event.toString());
        return super.onTouchEvent(event);
    }

    /**
     * Home键监听
     */
    @Override
    public void onHomeKeyPressed() {
        Log.d(TAG, "###############onHomePressed()##################");
        //为了验证中途退出问题，暂时去掉监听
        //                FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, "finish 3,点击home键返回", "听说模考追踪中途finish", true);
        if (mp3Recorder != null && mp3Recorder.isRecording()) {
            isStopFlag = true;
            mp3Recorder.stop();
        }

        NewBaseListenSpeakActivity.this.finish();
    }


    /**
     * 用户作答结束处理
     */
    protected void userAnswerOver() {


        //做完题不管任何状态都跳到结果页面对状态处理
        //EpaperJumpManager.jumpToListenSpeakResult(R.string.listen_speak,
        //mActivity,  mDownLoadInfo,mModule,checkedResource,position,intentWorkId,mClassId, workTime ,mServiceId,mLswAnswerList,mExamData,
        //MainActivity.REQUEST_CODE_TO_DO_WORK,mWorkContents,lsMode);
        //为了与查看详情取资源匹配，同步其他地方，默认只有一个module Content

        if (null != mLswAnswerList) {
            Log.e(TAG, "##########mLswAnswerList.size()##############" + mLswAnswerList.size());
        }

        Log.d(TAG, "########## ListenSpeakUtil.getAnswerCardData(mResourceList).size()##############" + ListenSpeakUtil.getAnswerCardData(mResourceList).size());


        CWSys.setSharedBoolean(ListenSpeakUtil.getBeenToRedoPageRecord(mDownLoadInfo, mModule, position, intentWorkId, uuid), true);

        EpaperJumpManager.jumpLsRedo((BaseActivity) mActivity, R.string.listen_speak, mDownLoadInfo, mModule, checkedResource, position, intentWorkId, mClassId, workTime, mServiceId, mLswAnswerList, mExamData,
                mWorkContents, lsMode, isDoRecords, doWorkType, isCorrect, effectivDate);

        finish();

    }


    /**
     * 更新答题卡选中项
     */
    protected void updateAnswerCardSelect() {
        if (answerCardDialog != null && answerCardDialog.isShowing()
                && cardAdapter != null) {
            cardAdapter.setCurrSelected(mQuesTotalIndex);
            cardAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 展示答题卡窗口
     * 听说模考调试专用
     */
    protected void showAnswerCardDialog(final List<ResourceDetail> mResourceList, final Handler mRecorderHandler) {
        answerCardDialog = new Dialog(NewBaseListenSpeakActivity.this,
                R.style.MyDialogStyle_Dim);
        answerCardDialog.setCancelable(true);
        answerCardDialog.setCanceledOnTouchOutside(true);
        View contentView = View.inflate(NewBaseListenSpeakActivity.this,
                R.layout.answer_card, null);
        GridView gridview = (GridView) contentView
                .findViewById(R.id.gv_question_no);
        if (cardAdapter == null) {
            cardAdapter = new AnswerCardAdapter(NewBaseListenSpeakActivity.this,
                    ListenSpeakUtil.getAnswerCardData(mResourceList));
            gridview.setAdapter(cardAdapter);
        }
        cardAdapter.setCurrSelected(mQuesTotalIndex);
        cardAdapter.notifyDataSetChanged();
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                if (cardAdapter.getCurrSelected() != position) {
                    answerCardDialog.dismiss();
                    bottomProgress.reDraw(position);
                    bottomNo.setHint(getString(R.string.show_bottom_no,
                            bottomProgress.getCurrentPoint() + 1,
                            bottomProgress.getPoint()));

                    loadSwitchAnim();
                    cardAdapter.setCurrSelected(position);
                    cardAdapter.notifyDataSetChanged();

                    String tvNo = ((TextView) view).getText().toString();
                    // 切换小题
                    int index = tvNo.indexOf(".");
                    if (index == -1) {
                        // answerCardDialog.dismiss();
                        // return;
                        index = 1;
                    }

                    ls_bottom_view.setPlayBtnState(false);

                    question_layout.optionsLayoutRemoveAllViews();
                    question_layout.imgContainerSetVisibility(View.GONE);

                    switchRelease(mRecorderHandler);

                    question_layout.setSmallQuestionStem(null);
                    question_layout.setChildQuestionStem(null, isNewVersion);

                    // 总下标
                    mQuesTotalIndex = position;
                    // 选择的大题
                    int bigQuIndex = Integer.parseInt(tvNo.substring(0, index));
                    if (bigQuIndex != mBigQuesIndex + 1) {// 不处于当前大题
                        mBigQuesIndex = bigQuIndex - 1;
                        switchBigQuestion(mResourceList);
                        startLoadBigQuestion(mResourceList);
                        return;
                    }

                    int lastIndex = tvNo.lastIndexOf(".");

                    if (lastIndex == index) {// 说明没有子题
                        mSmallQuesIndex = Integer.parseInt(
                                tvNo.substring(index + 1, tvNo.length())) - 1;
                        mChildQuesIndex = -1;
                        Questions smallQuestion = mResourceList
                                .get(mBigQuesIndex).getQuestions()
                                .get(mSmallQuesIndex);
                        if (ListenSpeakUtil.questionTypeIsExist(smallQuestion.getType())) {
                            switchSmallQuestion(mResourceList, smallQuestion);// 切换小题
                        } else {
                            showToastError(R.string.question_type_not_exist);
                        }
                    } else {// 有子题
                        // 选择的小题
                        int smallQuIndex = Integer
                                .parseInt(tvNo.substring(index + 1, lastIndex));
                        Questions smallQuestion = mResourceList
                                .get(mBigQuesIndex).getQuestions()
                                .get(mSmallQuesIndex);
                        if (!ListenSpeakUtil.questionTypeIsExist(smallQuestion.getType())) {
                            showToastError(R.string.question_type_not_exist);
                            return;
                        }
                        // 先判断是否处于当前小题
                        if (smallQuIndex != mSmallQuesIndex + 1) {// 不处于当前小题
                            mBigQuesIndex = smallQuIndex - 1;
                            startLoadSmallQuestion(mResourceList, smallQuestion);
                        }
                        // 切换子题
                        List<Questions> childQuesList = smallQuestion
                                .getChildren();
                        if (childQuesList != null && !childQuesList.isEmpty()) {
                            List<Questions> childQuestion = smallQuestion
                                    .getChildren();
                            if (childQuestion != null) {
                                int childQuesIndex = Integer
                                        .parseInt(tvNo.substring(lastIndex + 1,
                                                tvNo.length()))
                                        - 1;
                                Questions childQues = childQuestion
                                        .get(childQuesIndex);
                                if (!ListenSpeakUtil.questionTypeIsExist(childQues.getType())) {
                                    showToastError(
                                            R.string.question_type_not_exist);
                                    return;
                                }
                                mChildQuesIndex = childQuesIndex;
                                // 加载子题
                                switchChildQuestion(childQues, mResourceList);
                            }
                        }
                    }

                }
            }
        });
        answerCardDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface dialog) {
                cardAdapter = null;
            }
        });
        answerCardDialog.setContentView(contentView);
        answerCardDialog.show();
    }


    protected void startRecordTimeCount() {
        //录音倒计时
        removeHandlerMsg(ListenSpeakUtil.HandlerWhat.UPDATE_TIME, mHandler);
        mHandler.sendEmptyMessage(ListenSpeakUtil.HandlerWhat.UPDATE_TIME);
    }

    //做题总计时
    protected void startTotalCount() {
        mHandler.sendEmptyMessage(ListenSpeakUtil.HandlerWhat.TOTAL_TIMER);//开始计时
    }

    /**
     * 切换的时候释放资源
     * 口头作文未开始
     * 显示计时
     * 移除消息队列
     */
    protected void switchRelease(Handler mRecorderHandler) {
        isShowTime = true;
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            //继续计时
            mHandler.sendEmptyMessage(
                    ListenSpeakUtil.HandlerWhat.TOTAL_TIMER);
        }
        if (mRecorderHandler != null) {
            mRecorderHandler.removeCallbacksAndMessages(null);
        }
        AudioPlayer.getInstance().stop();
        ls_bottom_view.microRecordingSetVisibility(View.GONE);
        ls_bottom_view.hideTimerAnimation();
    }


    /**
     * 缓存大题题号
     *
     * @param isSaveBigQuesIndex 是否保存大题题号
     */
    protected void serializeBigQuesIndex(boolean isSaveBigQuesIndex, int mBigQuesIndex) {
        if (isSaveBigQuesIndex) {
            CWSys.setSharedInt(ListenSpeakUtil.getSaveQuesNoKey(mDownLoadInfo, mModule, position, intentWorkId, uuid), mBigQuesIndex);
        }
    }

    /**
     * 打印当前状态
     */
    protected void printState() {
        Log.e(TAG, "state：" + status);
    }


    /**
     * 移除Handler消息
     *
     * @param what
     */
    protected void removeHandlerMsg(int what, Handler mHandler) {
        if (mHandler.hasMessages(what)) {
            mHandler.removeMessages(what);
        }
    }

    /**
     * @param bigQuesIndex    当前大题下标
     * @param workTime        作业用时
     * @param mQuesTotalIndex 题目总下标
     * @param mSmallQuesIndex 当前小题下标
     * @param status          当前状态
     */
    protected void serializeRecord(int bigQuesIndex, int workTime, int mQuesTotalIndex, int mSmallQuesIndex, ListenSpeakUtil.State status) {
        //缓存用户答案和音频上传状态的方法
        SerializableManager.getInstance().serialize(ListenSpeakUtil.getSaveLsAnswerListKey(mDownLoadInfo, mModule, position, intentWorkId, uuid), mLswAnswerList);

        CWSys.setSharedInt(ListenSpeakUtil.getSaveTotalIndexKey(mDownLoadInfo, mModule, position, intentWorkId, uuid), mQuesTotalIndex);
        CWSys.setSharedInt(ListenSpeakUtil.getSaveQuesNoKey(mDownLoadInfo, mModule, position, intentWorkId, uuid), bigQuesIndex);
        CWSys.setSharedInt(ListenSpeakUtil.getSaveSmallQuesKey(mDownLoadInfo, mModule, position, intentWorkId, uuid), mSmallQuesIndex);
        CWSys.setSharedInt(ListenSpeakUtil.getSaveStatusQuesKey(mDownLoadInfo, mModule, position, intentWorkId, uuid), ListenSpeakUtil.getStateIndex(status));
        CWSys.setSharedInt(ListenSpeakUtil.getSaveTime(mDownLoadInfo, mModule, position, intentWorkId, uuid), workTime);
        CWSys.setSharedInt(ListenSpeakUtil.getSaveQuesCountKey(mDownLoadInfo, mModule, position, intentWorkId, uuid), mExamData.getItems().size());
    }


    //保存用户答案记录及缓存
    protected void startMakeScoreRequestAndSaveAnswer(LswAnswer lswAnswer) {   //如果已经存在则过滤删除
        addAnswerToAnswerList(lswAnswer);

        //缓存列表
        serializeRecord(mBigQuesIndex, workTime, mQuesTotalIndex, mSmallQuesIndex, status);
        //SaveLsUserAnswerList();
        //上报作业进度
        setDoworkProgress();
        //选择填空题不再上传
        if (lswAnswer.getAnswerType() == Questions.AnswerType.QUESTION_TYPE_CHOICE || lswAnswer.getAnswerType() == Questions.AnswerType.QUESTION_TYPE_FILL_BLANK) {

            return;
        } else {
            //音频上传
            onUploadStateDeal(lswAnswer);
        }
    }

    /**
     * 设置做作业进度
     */
    protected void setDoworkProgress() {
        if (effectivDate <= 0 || doWorkType == 1) {
            return;
        }
        LswProgress lswProgress = new LswProgress();
        lswProgress.setTotal(mQuesTotal);
        lswProgress.setWorkId(intentWorkId);
        lswProgress.setContentId(mWorkContents.getContentId());
        lswProgress.setEffectivDate(effectivDate);
        lswProgress.setProgress(mLswAnswerList.size());
        lswProgress.setWorkLong(workTime);
        lswProgress.setUuid(uuid);
        onUploadDoworkProgress(lswProgress);
    }

    protected void addAnswerToAnswerList(LswAnswer lswAnswer) {
        Iterator<LswAnswer> iterator = mLswAnswerList.iterator();
        while (iterator.hasNext()) {
            LswAnswer l = iterator.next();
            if (l.getVersionId().equals(lswAnswer.getVersionId())) {
                Log.d("removeexist", "#############remove exist#############");
                iterator.remove();
            }
        }
        mLswAnswerList.add(lswAnswer);
    }


    private void onUploadStateDeal(final LswAnswer lswAnswer) {
//        lswAnswer.setUploadState(LswAnswer.UPLOADING);
        if (!EConstants.IS_YOUKE) {
            LswDao.getInstance().submitMakeScore(lswAnswer, isCorrect, new BaseCallBack() {
                @Override
                public void success(Object data) {
                    CWLog.d(TAG, "###########上传音频成功############" + lswAnswer.getVersionId());

                    RecordSubmitPart recordSubmitPart = (RecordSubmitPart) data;

                    if (null != recordSubmitPart && null != mLswAnswerList) {
                        for (int i = 0; i < mLswAnswerList.size(); i++) {
                            if (mLswAnswerList.get(i).getVersionId().equals(lswAnswer.getVersionId())) {
                                mLswAnswerList.get(i).setUploadState(LswAnswer.SUCCESS);
                                mLswAnswerList.get(i).setRecordSubmitPart(recordSubmitPart);
                                serializeRecord(mBigQuesIndex, workTime, mQuesTotalIndex, mSmallQuesIndex, status);
                            }
                        }
                    }
                }

                @Override
                public void failed(int errorCode, Object data) {
                    failed(data);
                }

                @Override
                public void failed(Object data) {

                    CWLog.d(TAG, "###########上传音频失败############" + lswAnswer.getVersionId());
                    if (data != null) {
                        FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, data.toString(), "听说模考上传语音评分失败：" + lswAnswer.getVersionId() + getUrl());
                    }

                    if (null != mLswAnswerList) {
                        for (int i = 0; i < mLswAnswerList.size(); i++) {
                            if (mLswAnswerList.get(i).getVersionId().equals(lswAnswer.getVersionId())) {
                                mLswAnswerList.get(i).setUploadState(LswAnswer.FAIL);
                            }
                        }
                    }

                }
            });
        }


    }

    private void onUploadDoworkProgress(final LswProgress lswProgress) {
        LswDao.getInstance().onUploadDoworkProgress(lswProgress, new BaseCallBack() {
            @Override
            public void success(Object data) {
                CWLog.d(TAG, "###########上传做作业进度成功############" + lswProgress.toString());
                CWSys.setSharedBoolean(ListenSpeakUtil.getStartDateIsUploadSaveKey(mDownLoadInfo, mModule, position, intentWorkId, doWorkType), true);
            }

            @Override
            public void failed(int errorCode, Object data) {
                failed(data);
            }

            @Override
            public void failed(Object data) {

                CWLog.d(TAG, "###########上传做作业进度失败############" + lswProgress.toString());
                if (data != null) {
                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, data.toString(), "听说模考上传语音评分失败：" + lswProgress.toString() + getUrl());
                }
            }
        });

    }

    /**
     * 是否还有文件上传中
     *
     * @return
     */
    private boolean isHashUploading() {
        for (LswAnswer lswAnswer : mLswAnswerList) {
            if (lswAnswer.getUploadState() == LswAnswer.UPLOADING) {
                return true;
            }
        }
        return false;
    }

    /**
     * 是否还有文件上传失败
     *
     * @return
     */
    private boolean isHashUploadFail() {
        for (LswAnswer lswAnswer : mLswAnswerList) {
            if (lswAnswer.getUploadState() == LswAnswer.FAIL) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取选择填空的答案和记录
     */
    private LswAnswer getChildOrFillBlankOrChoice(List<ResourceDetail> mResourceList, Questions smallOrChildQues) {
        // 当前小题 或者是子题
        if (ListenSpeakUtil.questionTypeIsExist(smallOrChildQues.getType())) {
            // 当前小题分
            List<QuestionScore> smallQuesScores = mResourceList.get(mBigQuesIndex).getScores();
            LswAnswer lswAnswer = new LswAnswer();
            lswAnswer.setQtype(smallOrChildQues.getType());
            lswAnswer.setWorkSaveUUid(uuid);
            lswAnswer.setTotalQuesIndex(totalQuesIndex);
            lswAnswer.setQuesNo(quesNo);
            lswAnswer.setBigQuesIndex(bigQuesIndex);
            lswAnswer.setVersionId(smallOrChildQues.getVersionId());
            if (isCorrect && null != mWorkContents) {
                lswAnswer.setDoWorkId(mWorkContents.getDoWorkId());
            }
            //选择填空不需要上传，默认成功
            lswAnswer.setUploadState(LswAnswer.SUCCESS);
            CWLog.d(TAG, "########setAnswerType###########" + smallOrChildQues.getType());


            for (QuestionScore q : smallQuesScores) {
                if (q.getQuestionVersionId().equals(smallOrChildQues.getVersionId())) {
                    lswAnswer.setRefScore(q.getScore());
                }
            }
//            lswAnswer.setAnswerType(smallOrChildQues.getType());
            // 添加答案  word_checked
            if (smallOrChildQues.getType() == Questions.QuestionType.QUESTION_TYPE_CHOICE) {
                //答案类型不是题目类型，选择题2，
                lswAnswer.setAnswerType(Questions.AnswerType.QUESTION_TYPE_CHOICE);

                List<AnswerContent> answerContents = new ArrayList<AnswerContent>();
                AnswerContent answerContent = new AnswerContent();
//                answerContent.setAnswerType(smallOrChildQues.getType());
                answerContent.setSid(0);


                List<OptionInfo> optionInfos = smallOrChildQues.getOptions();
                //找出正确答案ID  只适用单选
                if (null != optionInfos && optionInfos.size() > 0) {

                    for (OptionInfo o : optionInfos) {
                        //正确答案
                        if (o.getIsAnswer() == 1) {

                            answerContent.setRefAnswer(o.getId());
                        }
                    }
                }
                OptionInfo checkedOptionInfo;

                checkedOptionInfo = question_layout.getChoicOptionInfo();

                if (null != checkedOptionInfo) {
                    CWLog.d(TAG, "#########选择题作答 id##########" + checkedOptionInfo.getId());
                    answerContent.setContent(checkedOptionInfo.getId());
                    answerContents.add(answerContent);
                    lswAnswer.setAnswerContents(answerContents);
                    return lswAnswer;
                } else {
                    //未作答，未作答精确到小题
//                    CWLog.d(TAG, "########选择题未作答###########");
//                    answerContent.setContent("");
//                    answerContents.add(answerContent);
//                    lswAnswer.setAnswerContents(answerContents);
//                    mChoiceAnswerList.add(lswAnswer);
//                    return null;

                    answerContent.setContent("");
                    answerContents.add(answerContent);
                    lswAnswer.setAnswerContents(answerContents);
                    lswAnswer.setAnswer(false);
                    return lswAnswer;
                }


            } else if (smallOrChildQues.getType() == Questions.QuestionType.QUESTION_TYPE_FILL_BLANK) {
                //填空
                if (question_layout.getBlankAnswer() != null) {
                    lswAnswer.setAnswerType(Questions.AnswerType.QUESTION_TYPE_FILL_BLANK);
                    List<AnswerContent> answerContents = question_layout.getBlankAnswer();
                    lswAnswer.setAnswerContents(answerContents);
                    return lswAnswer;
                }

            }
        }

        //题目类型不存在返回空
        return null;
    }

    /**
     * 解决module 为空时的崩溃问题
     *
     * @param module
     * @param downLoadInfo
     */
    private void deleteResourceIfNull(Module module, final DownLoadInfo downLoadInfo) {
        if (module == null) {
            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, "Intent 获取数据空", "听说模考从上个页面获取资源为空Module，lsMode：" + lsMode);
            try {
                ThreadTask.getInstance().executorDBThread(new Runnable() {
                    @Override
                    public void run() {
                        if (downLoadInfo != null) {
                            DownLoadDB.deleteData(downLoadInfo);
                            FileUtils.delete(downLoadInfo.getSavePath());
                        }

                    }
                }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);

            } catch (Exception e) {
                e.printStackTrace();
                FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_LISTEN_SPEAK_WORK, "清理缓存资源异常：" + e.getMessage(), "听说模考从上个页面获取资源为空lsMode：" + lsMode);
            }

            if (mp3Recorder != null && mp3Recorder.isRecording()) {
                isStopFlag = true;
                mp3Recorder.stop();
            }
            NewBaseListenSpeakActivity.this.finish();
            return;
        }
    }
}
